package xyz.hubery.stream;

import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;
import xyz.hubery.disruptor.DisruptorTemplate;
import xyz.hubery.disruptor.OrderEvent;
import xyz.hubery.disruptor.OrderEventHandler;
import xyz.hubery.domain.EntrustOrder;
import xyz.hubery.domain.Order;
import xyz.hubery.enums.OrderStatus;
import xyz.hubery.util.BeanUtil;

/**
 * 消息队列监听器(消费者)
 */
@Service
@Slf4j
public class MessageConsumerListener {

    @Autowired
    private DisruptorTemplate disruptorTemplate;
    @Autowired
    private EventHandler<OrderEvent>[] eventHandlers;

    /**
     * 接收委托单信息
     * @param order
     */
    @StreamListener("order-in")
    public void handleMessage(EntrustOrder order) {
        log.info("接收到了委托单:{}", order);
        disruptorTemplate.onData(BeanUtil.entrustOrderToOrder(order));
    }

    /**
     * 撤销了一个订单, 不直接创建线程来删除，会引发并发问题，加锁会影响性能
     * 这里我们直接将该删除委托单也加入到队列中交由撮合服务处理
     * 撮合前进行过滤，如果是删除委托单，则进行删除
     * 删除成功则发送消息，告知删除完毕
     */
    @StreamListener("rem-order-in")
    public void remOrderById(EntrustOrder entrustOrder) {
        log.info("撤销委托单:{}", entrustOrder);
        Order order = BeanUtil.entrustOrderToOrder(entrustOrder);
        order.setOrderStatus(OrderStatus.CANCELED.getCode()); // 设置状态为已取消
        disruptorTemplate.onData(order);
    }

}
